package com.xqc.algorithm;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;

/**
* @dateTime 创建时间：2020年8月19日 上午10:19:06
* @version V1.0.0
* 类说明 自定义分表算法,尾数0-5存表t_user_1，6-9存表t_user_2
*/
public class MyPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long>{

	private static final List<String> PARAM_LIST = Arrays.asList("0","1","2","3","4","5");
	
	@Override
	public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
		//availableTargetNames拆分出来的物理表【t_user_1,t_user_2】，shardingValue分片字段的值
		for (String availableTargetName : availableTargetNames) {
			String value = "2" ;
			//尾数0-5存表t_user_1，6-9存表t_user_2
			 String colValue = shardingValue.getValue().toString();
			 String subLast = shardingValue.getValue().toString().substring(colValue.length()-1, colValue.length());
			 if(PARAM_LIST.contains(subLast)){
				 value = "1";
			 }
			if(availableTargetName.endsWith(value)){
				return availableTargetName;
			}
		}
		throw new IllegalArgumentException();
	}

}
